import requests
import time
import os
import logging
from pathlib import Path

# 配置日志系统
script_dir = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_dir, 'udpxy_monitor.log')

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(log_file),  # 文件日志
        logging.StreamHandler()  # 控制台日志
    ]
)
logger = logging.getLogger(__name__)
 
# 多播流地址
STREAM_URL = "http://10.0.0.9:4022/rtp/239.45.1.21:5140"
# 检测间隔（秒）
CHECK_INTERVAL = 60
# 请求超时时间（秒）
TIMEOUT = 5


def check_stream():
    """检查多播流是否正常"""
    try:
        # 发送HTTP GET请求
        response = requests.get(STREAM_URL, timeout=TIMEOUT, stream=True)
        # 检查状态码
        if response.status_code == 200:
            # 检查是否能读取到数据
            response.raw.read(1024)  # 尝试读取1KB数据
            return True
        else:
            logger.warning(f"异常状态码: {response.status_code}")
            return False
    except (requests.RequestException, ConnectionError) as e:
        logger.error(f"流检测失败: {str(e)}", exc_info=True)
        return False
    except Exception as e:
        logger.critical(f"未预期的检测错误: {str(e)}", exc_info=True)
        return False

def restart_udpxy():
    """重启udpxy服务"""
    try:
        logger.info("正在重启udpxy服务...")
        result = os.system("/etc/init.d/udpxy restart")
        if result == 0:
            logger.info("udpxy服务重启成功")
        else:
            logger.error(f"重启失败，返回码: {result}")
    except Exception as e:
        logger.error(f"重启异常: {str(e)}", exc_info=True)
        raise

def main():
    logger.info("多播流监控启动")
    logger.debug(f"监控参数 => URL: {STREAM_URL}, 间隔: {CHECK_INTERVAL}s, 超时: {TIMEOUT}s")
 
    while True:
        try:
            if check_stream():
                logger.debug("多播流检测正常")
            else:
                logger.warning("多播流异常，触发重启")
                restart_udpxy()
                # 重启后等待额外时间让服务稳定
                time.sleep(5)
 
            time.sleep(CHECK_INTERVAL)
 
        except KeyboardInterrupt:
            logger.info("用户中断监控进程")
            break
        except Exception as e:
            logger.critical(f"监控进程崩溃: {str(e)}", exc_info=True)
            raise

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        logger.error(f"主程序异常: {str(e)}", exc_info=True)
    finally:
        logger.info("多播流监控已停止")